#
# THIS FILE IS GENERATED, PLEASE DO NOT EDIT.
#

# Copyright 2022 Flant JSC
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
#     http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.

name: 'Deploy web to stage'

on:
  workflow_dispatch:
    inputs:
      issue_id:
        description: 'ID of issue where label was set'
        required: true
      issue_number:
        description: 'Number of issue where label was set'
        required: true
      comment_id:
        description: 'ID of comment in issue where to put workflow run status'
        required: true
      ci_commit_ref_name:
        description: 'Git ref name for image tags'
        required: false
      pull_request_ref:
        description: 'Git ref for checkout PR sources'
        required: false
      pull_request_sha:
        description: 'Git SHA for restoring artifacts from cache'
        required: false
      pull_request_head_label:
        description: 'Head label of pull request. e.g. my_repo:my_feature_branch'
        required: false

env:

  # <template: werf_envs>
  WERF_CHANNEL: "ea"
  WERF_ENV: "FE"
  TEST_TIMEOUT: "15m"
  # Use fixed string 'sys/deckhouse-oss' for repo name. ${CI_PROJECT_PATH} is not available here in GitHub.
  DEV_REGISTRY_PATH: "${{ secrets.DECKHOUSE_DEV_REGISTRY_HOST }}/sys/deckhouse-oss"
  # Registry for additional repositories used for testing Github Actions workflows.
  GHA_TEST_REGISTRY_PATH: "ghcr.io/${{ github.repository }}"
  # </template: werf_envs>

# Cancel in-progress jobs for the same tag/branch.
concurrency:
  group: ${{ github.workflow }}-${{ github.ref }}-stage
  cancel-in-progress: true

jobs:

  # <template: git_info_job>

  git_info:
    name: Get git info
    runs-on: ubuntu-latest
    outputs:
      ci_commit_tag: ${{ steps.git_info.outputs.ci_commit_tag }}
      ci_commit_branch: ${{ steps.git_info.outputs.ci_commit_branch }}
      ci_commit_ref_name: ${{ steps.git_info.outputs.ci_commit_ref_name }}
      ci_commit_ref_slug: ${{ steps.git_info.outputs.ci_commit_ref_slug }}
      ref_full: ${{ steps.git_info.outputs.ref_full }}
      github_sha: ${{ steps.git_info.outputs.github_sha }}
      pr_number: ${{ steps.git_info.outputs.pr_number }}
    # Skip the CI for automation PRs, e.g. changelog
    if: ${{ github.event.pull_request.user.login != 'deckhouse-BOaTswain' }}
    steps:
      - id: git_info
        name: Get tag name and SHA
        uses: actions/github-script@v6.4.1
        with:
          script: |
            const { GITHUB_REF_TYPE, GITHUB_REF_NAME, GITHUB_REF } = process.env

            let refSlug = ''
            let refName = ''
            let refFull = ''
            let githubBranch = ''
            let githubTag = ''
            let githubSHA = ''
            let prNumber = ''
            if (context.eventName === "workflow_dispatch" && context.payload.inputs && context.payload.inputs.pull_request_ref) {
              // Trigger: workflow_dispatch with pull_request_ref.
              // Extract pull request number from 'refs/pull/<NUM>/merge'
              prNumber = context.payload.inputs.pull_request_ref.replace('refs/pull/', '').replace('/merge', '').replace('/head', '')

              refSlug       = `pr${prNumber}`
              refName       = context.payload.inputs.ci_commit_ref_name
              refFull       = context.payload.inputs.pull_request_ref
              githubBranch  = refName
              githubSHA     = context.payload.inputs.pull_request_sha
              core.info(`workflow_dispatch event: set git info from inputs. inputs: ${JSON.stringify(context.payload.inputs)}`)
            } else if (context.eventName === "pull_request" || context.eventName === "pull_request_target" ) {
              // For PRs from forks, tag images with `prXXX` to avoid clashes between branches.
              const targetRepo = context.payload.repository.full_name;
              const prRepo = context.payload.pull_request.head.repo.full_name
              const prRef = context.payload.pull_request.head.ref

              refSlug = `pr${context.issue.number}`;
              refName = (prRepo === targetRepo) ? prRef : refSlug;
              refFull = `refs/pull/${context.issue.number}/head`
              githubBranch = refName
              githubSHA = context.payload.pull_request.head.sha
              core.info(`pull request event: set git info from pull_request.head. pr:${prRepo}:${prRef} target:${targetRepo}:${context.ref}`)
              prNumber = context.issue.number
            } else {
              // Other triggers: workflow_dispatch without pull_request_ref, schedule, push...
              // refName is 'main' or tag name, so slugification is not necessary.
              refSlug       = GITHUB_REF_NAME
              refName       = GITHUB_REF_NAME
              refFull       = GITHUB_REF
              githubTag     = GITHUB_REF_TYPE == "tag"    ? refName : ""
              githubBranch  = GITHUB_REF_TYPE == "branch" ? refName : ""
              githubSHA     = context.sha
              core.info(`${context.eventName} event: set git info from context: ${JSON.stringify({GITHUB_REF_NAME, GITHUB_REF_TYPE, sha: context.sha })}`)
            }

            core.setCommandEcho(true)
            core.setOutput('ci_commit_ref_slug', refSlug)
            core.setOutput('ci_commit_ref_name', refName)
            core.setOutput(`ci_commit_tag`, githubTag)
            core.setOutput(`ci_commit_branch`, githubBranch)
            core.setOutput(`ref_full`, refFull)
            core.setOutput('github_sha', githubSHA)
            core.setOutput('pr_number', prNumber)
            core.setCommandEcho(false)

  # </template: git_info_job>

  # <template: check_label_job>
  check_label:
    name: Check label
    runs-on: ubuntu-latest
    outputs:
      should_run: ${{ steps.check_label.outputs.should_run }}
      labels: ${{ steps.check_label.outputs.labels }}
    steps:

      # <template: checkout_step>
      - name: Checkout sources
        uses: actions/checkout@v3.5.2

      # </template: checkout_step>
      - id: check_label
        name: Check labels on push
        uses: actions/github-script@v6.4.1
        with:
          script: |
            const labelType = 'deploy-web';
            const labelSubject = 'stage';

            const ci = require('./.github/scripts/js/ci');
            return await ci.checkLabel({github, context, core, labelType, labelSubject});
  # </template: check_label_job>

  run_web_deploy:
    needs:
    - check_label
    - git_info
    if: needs.check_label.outputs.should_run == 'true'
    name: Deploy site
    runs-on: [self-hosted, regular]
    steps:

      # <template: started_at_output>
      - name: Job started timestamp
        id: started_at
        run: |
          unixTimestamp=$(date +%s)
          echo "started_at=${unixTimestamp}" >> $GITHUB_OUTPUT
      # </template: started_at_output>

      # <template: checkout_from_event_ref_step>
      - name: Checkout sources
        uses: actions/checkout@v3.5.2
        with:
          ref: ${{ github.event.inputs.pull_request_ref || github.event.ref }}
          fetch-depth: 0
      # </template: checkout_from_event_ref_step>
      # <template: update_comment_on_start>
      - name: Update comment on start
        if: ${{ github.event_name == 'workflow_dispatch' && !!github.event.inputs.issue_number }}
        uses: actions/github-script@v6.4.1
        with:
          github-token: ${{secrets.BOATSWAIN_GITHUB_TOKEN}}
          retries: 3
          script: |
            const name = 'Deploy web to stage';

            const ci = require('./.github/scripts/js/ci');
            return await ci.updateCommentOnStart({github, context, core, name})

      # </template: update_comment_on_start>

      # <template: login_dev_registry_step>
      - name: Check dev registry credentials
        id: check_dev_registry
        env:
          HOST: ${{secrets.DECKHOUSE_DEV_REGISTRY_HOST}}
        run: |
          if [[ -n $HOST ]]; then
            echo "has_credentials=true" >> $GITHUB_OUTPUT
            echo "web_registry_path=${{secrets.DECKHOUSE_DEV_REGISTRY_HOST }}/deckhouse/site" >> $GITHUB_OUTPUT
          fi
      - name: Login to dev registry
        uses: docker/login-action@v2.1.0
        if: ${{ steps.check_dev_registry.outputs.has_credentials == 'true' }}
        with:
          registry: ${{ secrets.DECKHOUSE_DEV_REGISTRY_HOST }}
          username: ${{ secrets.DECKHOUSE_DEV_REGISTRY_USER }}
          password: ${{ secrets.DECKHOUSE_DEV_REGISTRY_PASSWORD }}
          logout: false
      # </template: login_dev_registry_step>

      # <template: login_readonly_registry_step>
      - name: Check readonly registry credentials
        id: check_readonly_registry
        env:
          HOST: ${{secrets.DECKHOUSE_REGISTRY_READ_HOST}}
        run: |
          if [[ -n $HOST ]]; then
            echo "has_credentials=true" >> $GITHUB_OUTPUT
            echo "web_registry_path=${{secrets.DECKHOUSE_REGISTRY_READ_HOST }}/deckhouse/site" >> $GITHUB_OUTPUT
          fi
      - name: Login to readonly registry
        uses: docker/login-action@v2.1.0
        if: ${{ steps.check_readonly_registry.outputs.has_credentials == 'true' }}
        with:
          registry: ${{ secrets.DECKHOUSE_REGISTRY_READ_HOST }}
          username: ${{ secrets.DECKHOUSE_REGISTRY_READ_USER }}
          password: ${{ secrets.DECKHOUSE_REGISTRY_READ_PASSWORD }}
          logout: false
      # </template: login_readonly_registry_step>

      # <template: deploy_site_template>
      - name: Deploy site to stage
        uses: werf/actions/converge@43075e4ab81952b181d33e125ef15b9c060a782e
        with:
          channel: ${{env.WERF_CHANNEL}}
          kube-config-base64-data: "${{ secrets.KUBECONFIG_BASE64_DEV }}"
          env: web-stage
        env:
          WERF_REPO: ${{ steps.check_dev_registry.outputs.web_registry_path }}
          WERF_DIR: "docs/site"
          WERF_RELEASE: "deckhouse-site"
          WERF_NAMESPACE: deckhouse-web-stage
          WERF_SET_DOC_VERSION: "global.doc_version=${{ env.DOC_VERSION }}"
          WERF_SET_ACTIVE_RELEASE: "global.active_release=v1"
          WERF_SET_URL: "global.url=deckhouse.stage.flant.com"
          WERF_SET_URL_RU: "global.url_ru=deckhouse.ru.stage.flant.com"
          WERF_SET_WEB_ENV: "web.env=web-stage"
          WERF_SET_DOMAIN_MAP: "global.domain_map=eyJlbiIgOiAiZGVja2hvdXNlLnN0YWdlLmZsYW50LmNvbSIsICJydSIgOiAiZGVja2hvdXNlLnJ1LnN0YWdlLmZsYW50LmNvbSJ9"
          WERF_SET_DCNAME: "web.dc_name=dev"
          DOC_API_KEY: "${{secrets.DOC_API_KEY}}"
          DOC_API_URL: "${{vars.DOC_API_URL}}"
          WERF_SET_MODULE_WATCHER_AUTHS: "global.moduleWatcherAuths=${{ secrets.MODULE_WATCHER_AUTHS }}"
      # </template: deploy_site_template>

      # <template: doc_version_template>
      - name: Set documentation version
        env:
          CI_COMMIT_TAG: ${{needs.git_info.outputs.ci_commit_tag}}
        run: |
          echo "DOC_VERSION=${CI_COMMIT_TAG:-latest}" >> $GITHUB_ENV
      # </template: doc_version_template>
      # <template: deploy_doc_template>
      - name: Deploy documentation to stage
        uses: werf/actions/converge@43075e4ab81952b181d33e125ef15b9c060a782e
        with:
          channel: ${{env.WERF_CHANNEL}}
          kube-config-base64-data: "${{ secrets.KUBECONFIG_BASE64_DEV }}"
          env: web-stage
        env:
          WERF_REPO: ${{ steps.check_dev_registry.outputs.web_registry_path }}
          WERF_DIR: "docs/documentation"
          WERF_RELEASE: "deckhouse-doc-${{ env.DOC_VERSION }}"
          WERF_NAMESPACE: deckhouse-web-stage
          WERF_SET_DOC_VERSION: "global.doc_version=${{ env.DOC_VERSION }}"
          WERF_SET_URL: "global.url=deckhouse.stage.flant.com"
          WERF_SET_URL_RU: "global.url_ru=deckhouse.ru.stage.flant.com"
          WERF_SET_WEB_ENV: "web.env=web-stage"
          WERF_SET_DCNAME: "web.dc_name=dev"
      # </template: deploy_doc_template>

      # <template: update_comment_on_finish>
      - name: Update comment on finish
        id: update_comment_on_finish
        if: ${{ always() && github.event_name == 'workflow_dispatch' && !!github.event.inputs.issue_number }}
        env:
          NEEDS_CONTEXT: ${{ toJSON(needs) }}
          JOB_CONTEXT: ${{ toJSON(job) }}
          STEPS_CONTEXT: ${{ toJSON(steps) }}
        uses: actions/github-script@v6.4.1
        with:
          github-token: ${{secrets.BOATSWAIN_GITHUB_TOKEN}}
          retries: 3
          script: |
            const statusConfig = 'job,final';
            const name = 'Deploy web to stage';
            const needsContext = JSON.parse(process.env.NEEDS_CONTEXT);
            const jobContext = JSON.parse(process.env.JOB_CONTEXT);
            const stepsContext = JSON.parse(process.env.STEPS_CONTEXT);
            let jobNames = null
            if (process.env.JOB_NAMES) {
              jobNames = JSON.parse(process.env.JOB_NAMES);
            }

            core.info(`needsContext: ${JSON.stringify(needsContext)}`);
            core.info(`jobContext: ${JSON.stringify(jobContext)}`);
            core.info(`stepsContext: ${JSON.stringify(stepsContext)}`);
            core.info(`jobNames: ${JSON.stringify(jobNames)}`);

            const ci = require('./.github/scripts/js/ci');
            return await ci.updateCommentOnFinish({github, context, core, statusConfig, name, needsContext, jobContext, stepsContext, jobNames});
      # </template: update_comment_on_finish>

